import { SEO } from '@/utils/seo'
import { extractDominantColorBase64 } from '@/utils'
import { useModel } from '@umijs/max'
import ExifReader from 'exifreader'
import React, { useEffect } from 'react'
import styles from './index.less'

const Item: React.FC<any> = ({ data, idx, setBgNo }) => {
  const [imgSrc, setImgSrc] = React.useState<string>('')
  const [mainColor, setMainColor] = React.useState<string>('')
  const [exif, setExif] = React.useState<any>({})
  const [onload, setOnload] = React.useState<boolean>(false)
  const itemRef = React.useRef<HTMLLIElement>(null)

  const fetchImageData = async () => {
    const response = await fetch(data.imgUrl)
    const buffer = await response.arrayBuffer()
    const tags = ExifReader.load(buffer)
    setExif(tags)

    // 转换为 base64
    const base64 = await new Promise<string>((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = () => {
        resolve(reader.result as string)
      }
      reader.onerror = reject
      reader.readAsDataURL(new Blob([buffer]))
    })
    setImgSrc(base64)
    extractDominantColorBase64(base64).then(setMainColor)
  }

  useEffect(() => {
    fetchImageData()
  }, [])

  useEffect(() => {
    if (onload) {
      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              setBgNo(idx + 1)
              document.body.style.setProperty('--bg-color', `rgba(${mainColor}, 0.8)`)
            }
          })
        },
        { threshold: 0.5 }
      )

      if (itemRef.current) {
        observer.observe(itemRef.current)
      }

      return () => {
        observer.disconnect()
      }
    }
  }, [onload])
  return (
    <li ref={itemRef} className={styles.item}>
      <div className={styles.posterOverlay}>
        {imgSrc && (
          <img
            loading="lazy"
            fetchPriority="low"
            decoding="async"
            data-maincolor={mainColor}
            className={styles.poster + ' works-imgel'}
            onLoad={() => {
              setOnload(true)
            }}
            src={imgSrc}
            alt={`Zusheng摄影作品 - ${data.title || `照片${idx + 1}`}`}
          />
        )}

        {/* 照片加载完成才显示参数 */}
        {onload && (
          <>
            <div className={styles.posterInfo}>
              <span>{exif?.LensModel?.description || ''}</span>
              <span>
                {exif?.FocalLength?.description}&nbsp;&nbsp;
                {exif?.FNumber?.description}&nbsp;&nbsp;
                {exif?.ExposureTime?.description && `${exif?.ExposureTime?.description}s`}
                &nbsp;&nbsp;
                {exif?.ISOSpeedRatings?.description && `ISO${exif?.ISOSpeedRatings?.description}`}
              </span>
            </div>
            <div className={styles.subTitle}>
              Shot&nbsp;on&nbsp;
              {exif?.Make?.description && exif?.Model?.description
                ? exif?.Model?.description?.includes(exif?.Make?.description)
                  ? exif?.Model?.description
                  : exif?.Make?.description + ' ' + exif?.Model?.description
                : `iPhone`}
            </div>
          </>
        )}
      </div>
    </li>
  )
}

const Photography = () => {
  const { photography } = useModel('global')
  const [bgNo, setBgNo] = React.useState<number>(0) // 背景序号

  useEffect(() => {
    return () => {
      document.body.style.setProperty('--bg-color', `rgb(234, 234, 235)`)
    }
  }, [])

  return (
    <>
      <SEO
        title="摄影作品 - Zusheng Studio"
        description="Zusheng Studio的摄影作品集，记录生活中的美好瞬间和创意视角。通过镜头捕捉的世界，分享摄影的艺术与技巧。"
        keywords="Zusheng,摄影,摄影作品,摄影技巧,创意摄影,照片,视觉艺术"
        url="https://zusheng.cc/photography"
      />
      <div className={styles.pagePhoto + ' page'}>
        <ul className={styles.list}>
          <div className={styles.no}>No.2025-031-{bgNo}</div>
          {photography?.length > 0 &&
            photography.map((data: any, idx) => (
              <Item key={data._id} idx={idx} data={data} setBgNo={setBgNo} />
            ))}
        </ul>
      </div>
    </>
  )
}

export default Photography
